/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.cms.security;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cms.setting.account.pojo.LoginAccount;
import com.cms.setting.account.service.LoginAccountService;
@Service
public class ShiroDbRealm extends AuthorizingRealm implements Realm, InitializingBean {
    private static Logger LOGGER = LoggerFactory.getLogger(ShiroDbRealm.class);
    @Autowired
    private LoginAccountService loginAccountService;
	/**
	 * 认证回调函数,登录时调用.
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
	}
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		/* 这里编写认证代码 */
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String email = token.getUsername();
        /*
         * UserManage u = new UserManage(); u.setCode(pageLoginName); UserManage member =
         * userManageService.selectUserManage(u); String mongoPass = member.getPwd(); if (mongoPass == null) { throw new
         * AuthenticationException(); }
         */
        LoginAccount loginAccount = new LoginAccount();
        loginAccount = loginAccountService.findByEmail(email);
        String pass = loginAccount.getPassword();
        String tokenPasswd = String.valueOf(token.getPassword());
        if (pass == null || !tokenPasswd.equals(pass)) {
            throw new IncorrectCredentialsException();
        }
        return new SimpleAuthenticationInfo(email, pass, getName());
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		/* 这里编写授权代码 */
		 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

         try {
        	String email = (String) super.getAvailablePrincipal(principals);
            LoginAccount loginAccount = new LoginAccount();
            loginAccount = loginAccountService.findByEmail(email);
            
     /*       Set<String> menuCodes = privilegeMngBiz.findAllPermissions(employee.getId());
            if(menuCodes != null && menuCodes.size() > 0){
            	info.addStringPermissions(menuCodes);
            }*/
            System.out.println("======================当前用户" + email + "拥有的权限:" + info.getStringPermissions());
            LOGGER.info("=============================当前用户" + email + "拥有的权限：" + info.getStringPermissions());
         } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("授权回调失败："+e.getMessage(), e);
         }

        return info;
	}

	/**
	 * 设定Password校验的Hash算法与迭代次数.
	 */
//	@PostConstruct
//	public void initCredentialsMatcher() {
//		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(CmAssociatorBizImpl.HASH_ALGORITHM);
//		matcher.setHashIterations(CmAssociatorBizImpl.HASH_INTERATIONS);
//
//		setCredentialsMatcher(matcher);
//	}




}
